/*
 * Copyright (c) 2002 Boris Pruessmann and others.
 * All rights reserved.   This program and the accompanying materials
 * are made available under the terms of the Common Public License v0.5
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/cpl-v05.html
 * 
 * Contributors:
 *    Boris Pruessmann - Initial implementation.
 */
package net.sourceforge.perforce.core.internal;

import net.sourceforge.perforce.core.PerforceCorePlugin;
import net.sourceforge.perforce.core.api.IPerforceServer;
import net.sourceforge.perforce.core.api.IPerforceServerManager;
import net.sourceforge.perforce.core.internal.api.Connection;
import net.sourceforge.perforce.core.internal.api.PerforceServer;

/**
  * @version 	$Revision: 67 $
  * @author		<a href="mailto:bpruessmann@users.sourceforge.net">Boris Pruessmann</a>
  */
public class ConnectionMonitorRunnable implements Runnable 
{
	// --------------------------------------------------------------------------- Private Variables
	
	/** Indicates whether the runnable should shutdown or not. */
	private boolean running = true;
	/** Stores the thread that runs the ConnectionMonitor. */
	private Thread thread;
	
	// ------------------------------------------------------------------------------ Public Methods
	
	/** @see java.lang.Runnable#run() */
	public void run() 
	{
		thread = Thread.currentThread();
		
		IPerforceServerManager manager = PerforceCorePlugin.getServerManager();		
		while (running)
		{
			try
			{
				IPerforceServer[] servers = manager.getPerforceServers();
				for (int i = 0; i < servers.length; i++)
				{
					if (servers[i] instanceof PerforceServer)
					{
						Connection connection = ((PerforceServer) servers[i]).getConnection();
						if (connection != null)
						{
							synchronized (connection)
							{
								long timeout = System.currentTimeMillis();
								if (connection.isOpen())
								{
									if (connection.getLastUse() + 5000 < timeout)
									{
										if (PerforceCorePlugin.getPlugin().isDebugging())
										{
											System.err.println(
												"Closing connection to " +             //$NON-NLS-1$
												servers[i].getPort());
										}
										connection.close();
									}
								}
							}
						}
					}
				}
			}
			catch (Throwable t)
			{
				PerforceCorePlugin.logError("Unexpected exception.", t);
			}
					
			try 
			{
				Thread.currentThread().sleep(1000);
			} 
			catch (InterruptedException e) 
			{
				// Ignored!
			}
		}
	}
	
	/** Call this method to start the Connection monitor. */ 
	public void startup()
	{
		new Thread(this, "Perforce Connection Monitor").start();
	}
	
	/** Call this method to shutdown the connection monitor. */
	public void shutdown()
	{
		running = false;
		try 
		{
			thread.join();
		} 
		catch (InterruptedException e) 
		{
			// Ignored!
		}
	}
}
